//
//  BankCardListViewController.m
//  HuLaQuan
//
//  Created by hok on 1/20/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//



#import "BankCardListViewController.h"

// Cells
#import "BankCardListCell.h"

// Jump To Controller
#import "AddCardCheckPasswordViewController.h"
#import "AddCardFirstInputPasswordController.h"
#import "BankCardDetailInfoController.h"

//Logic Model
#import "GetUserAccountInfoEngine.h"

@interface BankCardListViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *addButton;

@property (strong,nonatomic) NSMutableArray *cardList;

/**
 *  存储initPay
 */
@property (strong,nonatomic) NSDictionary *passwordInfo;

@property (strong,nonatomic) NSIndexPath *selectedIndexPath;


@property (nonatomic,strong) GetUserAccountInfoEngine *getUserAccountInfoEngine;
@end

static NSString * const BankCardListCellIdentifier = @"BankCardListCell";

@implementation BankCardListViewController

- (GetUserAccountInfoEngine *)getUserAccountInfoEngine
{
    if (!_getUserAccountInfoEngine) {
        _getUserAccountInfoEngine = [[GetUserAccountInfoEngine alloc] init];
    }
    return _getUserAccountInfoEngine;
}
- (NSMutableArray *)cardList
{
    if (!_cardList) {
        _cardList = [[NSMutableArray alloc] init];
    }
    return _cardList;
   
}
- (void)setupUI
{
    [self setupNavBackButton];
    
    self.tableView.backgroundColor = UIColorFromRGBA(kBackgroundColor, 1.0);

    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[BankCardListCell nib] forCellReuseIdentifier:BankCardListCellIdentifier];
    
    
    
    self.title = @"银行卡";
    
    
//    [self.cardList addObject:@{@"bankName":@"工商银行",@"cardType":@"储蓄32",@"cardNo":@"1897098723"}];
//    [self.cardList addObject:@{@"bankName":@"工商银行",@"cardType":@"储蓄12",@"cardNo":@"1897098723"}];
    
    [self updateUI];
    
    [self createNavigationBarRightBarButtonItemWithTitle:@"增加"];
}
- (void)rightAction
{
    NSLog(@"编辑");
    [self tapAddButton:nil];
}
- (void)setupFooterForTableView
{
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,1)];
    self.tableView.tableFooterView = v;
}

- (void)updateUI
{
    [self.tableView  setHidden:self.cardList.count ? NO:YES];
    [self.addButton setHidden:self.cardList.count ? YES:NO];
    
    [self.tableView reloadData];
    
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return kBankCardListCellHeight;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cardList.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return kUserCenterSectionHeaderHeight;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    BankCardListCell *cell = [tableView dequeueReusableCellWithIdentifier:BankCardListCellIdentifier
                                                           forIndexPath:indexPath];
    cell.cardBank.text = self.cardList[indexPath.row][@"bankName"];
    
    NSString *type = self.cardList[indexPath.row][@"accType"];
    cell.cardType.text = [self cardType:type];
    
    cell.cardNumber.text = [self formCardNumberToShow:self.cardList[indexPath.row][@"cardId"]];
    
    cell.cardImageName = self.cardList[indexPath.row][@"bankName"];
    return cell;

    
    
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.selectedIndexPath = indexPath;
    [self performSegueWithIdentifier:@"ShowBankCardInfoFromList" sender:self];
    
}

#pragma mark - Show Card Content Function
- (NSString *) cardType:(NSString *)typeString
{
    return [[typeString substringFromIndex:typeString.length - 5] isEqualToString:@"DEBIT"] ? @"储蓄卡" : @"信用卡";
}
- (NSString *)formCardNumberToShow:(NSString *)cardId
{
    NSString *result = nil;
    if (cardId.length && cardId.length > 5) {
        result = [NSString stringWithFormat:@"**** **** **** %@",[cardId substringFromIndex:cardId.length - 4]];
    }
    return result;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
- (IBAction)tapAddButton:(id)sender {
    if ([self.passwordInfo[@"initPay"] isEqualToString:@"true"]) {
        //初次设置支付密码
        [self performSegueWithIdentifier:@"ShowAddCardFirstInputPasswordFromCardList" sender:self];
    }else{
        
        //已经设置，验证支付密码
        [self performSegueWithIdentifier:@"ShowAddCheckPasswordFromCardList" sender:self];
    }
    
}


#pragma mark - CallBack

/**
 *  获取用户银行卡信息后，刷新银行卡列表
 *
 *  @param notification
 */
- (void)getUserAccountInfoFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
        if (messageDic[@"result"]) {
            
            self.passwordInfo = [messageDic[@"result"] objectForKey:kInitPayStatusKey];
            
            self.cardList = [[NSMutableArray alloc] initWithArray: messageDic[@"result"][@"cardList"]];
            
            NSLog(@"%@ %@ %@",messageDic[@"result"],self.passwordInfo ,self.cardList);
            
            [self updateUI];
            
        }
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getUserAccountInfoFinish:) name:@"GetUserAccountInfoFinish" object:nil];
    
    
    [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
    [self.getUserAccountInfoEngine getAccoutInfo];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"GetUserAccountInfoFinish" object:nil];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    if ([[segue identifier] isEqualToString:@"ShowBankCardInfoFromList"]) {
        BankCardDetailInfoController *controller = (BankCardDetailInfoController*) [segue destinationViewController];
        controller.cardInfo = self.cardList[self.selectedIndexPath.row];
        return;
    }
    
    
    
    
    if ([[segue identifier] isEqualToString:@"ShowAddCheckPasswordFromCardList"]) {
        AddCardCheckPasswordViewController *controller = (AddCardCheckPasswordViewController*) [segue destinationViewController];
        return;
    }
    
    if ([[segue identifier] isEqualToString:@"ShowAddCardFirstInputPasswordFromCardList"]) {
        AddCardFirstInputPasswordController *controller = (AddCardFirstInputPasswordController*) [segue destinationViewController];
        //controller.typeOfCheck = BindingCard;
        controller.type = PayPassword;
        controller.titleOfNav = kSetPayPasswordTitle;
        controller.titleOfPassword = kSetPayPasswordHint;
        return;
    }
}


@end
